<?php
/**
 * common repository file Created by PhpStorm.
 * User: wumengmeng
 * Date: 2019/10/26
 * Time: 09:59
 */

namespace HiCommon\Repository;

use DB;
use HiCommon\Model\StoreOrder;

class StoreOrderRepository extends BaseRepository
{
    public function base_model()
    {
        return new \HiCommon\Model\StoreOrder();
    }

    /**
     * 分页获取全部数据
     *
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_all($arr_option = [])
    {
        $model = new StoreOrder();
        if (!empty($arr_option['where']['range'])) {
            $range = explode(' - ', $arr_option['where']['range']);
            $model = $model->whereBetween('created_at', [$range[0], $range[1] . ' 23:59:59']);
            unset($arr_option['where']['range']);
        }

        return $model->commonget($arr_option);
    }


    /**
     * 分页获取全部数据
     *
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_all_wherein(array $ids, array $arr_option = [])
    {
        return StoreOrder::whereIn('shop_id', $ids)->commonget($arr_option);
    }


    /**
     * 分页获取数据
     *
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_list($arr_option = [])
    {
        $model = new StoreOrder();
        if (!empty($arr_option['where']['range'])) {
            $range = explode(' - ', $arr_option['where']['range']);
            $model = $model->whereBetween('created_at', [$range[0], $range[1] . ' 23:59:59']);
            unset($arr_option['where']['range']);
        }

        return $model->commonpage($arr_option);
    }

    /**
     * 通过where分页获取数据
     *
     * @param array $arr_where
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_list_by_where($arr_where, $arr_option = [])
    {
        $model = new StoreOrder();
        if (!empty($arr_where['created_at'])) {
            $model = $model->where('created_at', '>=', $arr_where['created_at']);
            $model = $model->where('created_at', '<=', $arr_where['created_at'] . ' 23:59:59');
            unset($arr_where['created_at']);
        }
        if (!empty($arr_where['or'])) {
            $model = $model->whereIn('status', $arr_where['or']);
            unset($arr_where['or']);
        }
        if (!empty($arr_where)) {
            $model = $model->where($arr_where);
        }
        return $model->commonpage($arr_option);
    }

    //售后（申请退款，申请退货）
    public function get_list_by_or_where($arr_where, $arr_option = [])
    {
        $model = new StoreOrder();
        if (!empty($arr_where['created_at'])) {
            $model = $model->where('created_at', '>=', $arr_where['created_at']);
            $model = $model->where('created_at', '<=', $arr_where['created_at'] . ' 23:59:59');
            unset($arr_where['created_at']);
        }

        return $model->where(function ($query) use ($arr_where) {
            if ($arr_where['or']) {
                $query->whereIn('status', $arr_where['or']);
                unset($arr_where['or']);
            }
        })->commonpage($arr_option);
    }

    /**
     * 根据条件统计数量
     *
     * @param array $arr_where
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_count_by_where($arr_where)
    {
        return StoreOrder::where($arr_where)->count();
    }


    /**
     * 根据条件统计数量  用户端统计数量使用
     *
     * @param array $arr_where
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_count_by_whereIn($arr_where)
    {
        return StoreOrder::where($arr_where)->whereIn('status', [1, 2])->count();
    }


    //获取正在进行中的订单
    public function count_order($arr_where)
    {
        return StoreOrder::where($arr_where)->where('status', '<', 4)->count();
    }

    //获取正在进行中的订单
    public function count_sale_order($arr_where)
    {
        return StoreOrder::where($arr_where)->whereIn('status', ['6', '7', '8', '9', '11', '12'])->count();
    }

    /**
     * 根据条件统计总和
     *
     * @param array $arr_where
     * @param string $s_field
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_sum_by_where($arr_where = [], $s_field = 'mark')
    {
        return StoreOrder::where($arr_where)->sum($s_field);
    }

    /**
     * 根据条件批量删除信息
     *
     * @param array $arr_where
     * @param bool $method
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function delete_by_where($arr_where = [], $method = false)
    {
        return StoreOrder::where($arr_where)->commondelete($method);
    }


    /**
     * 通过where获取一条数据
     *
     * @param array $arr_where
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_one_by_where($arr_where, $arr_option = [])
    {
        return StoreOrder::where($arr_where)->commonfirst($arr_option);
    }


    /**
     * 按用户统计数据（商户端用户列表专属）
     *
     * @param array $arr_where
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_user_list(array $arr_where, string $act = 'asc', array $user_ids = [])
    {
        $raw = \DB::raw("count('*') as total, sum(pay_amount) as pay_price , user_id ");
        return StoreOrder::select($raw)->where($arr_where)->where(
            function ($query)
            use ($user_ids) {
                if (count($user_ids) > 0 && $user_ids['key_word']) {
                    $query->whereIn('user_id', $user_ids);
                }
            })->orderBy('pay_amount', $act)->with('user')->groupBy('user_id')->paginate(15);
    }

    /**
     *  根据商铺分组获取数据
     *
     **/
    public function get_shop_list(array $arr_where)
    {
        $raw = \DB::raw(" shop_id ");
        return StoreOrder::select($raw)->where($arr_where)->with('shop')->groupBy('shop_id')->get();
    }


    /**
     * 添加一条数据
     *
     * @param array $arr_input
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function add_one($arr_input)
    {
        return StoreOrder::create($arr_input);
    }

    /**
     * 添加多条数据
     *
     * @param array $arr_data
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function add_many($arr_data)
    {
        return StoreOrder::insert($arr_data);
    }

    /**
     * 查询一条数据
     *
     * @param int $n_id
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_one(int $n_id, $arr_option = [])
    {
        return StoreOrder::commonfind($n_id, $arr_option);
    }

    /**
     * 更新或新建一条数据
     *
     * @param $arr_where
     * @param $arr_input
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function edit_or_create($arr_where, $arr_input)
    {
        $res = StoreOrder::where($arr_where)->first();
        if (is_null($res)) {
            StoreOrder::create(array_merge($arr_where, $arr_input));
        } else {
            StoreOrder::where($arr_where)->update($arr_input);
        }
        return StoreOrder::where($arr_where)->first();
    }

    /**
     * 修改一条数据
     *
     * @param array $arr_input
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function edit_one(array $map, array $arr_input)
    {
        return StoreOrder::where($map)->update($arr_input);
    }


    /**
     * 根据条件更新数据
     */
    public function edit_one_whereIn(array $map, array $arr_input)
    {
        return StoreOrder::whereIn($map['key'], $map['value'])->update($arr_input);
    }


    /**
     *  统计用户的订单信息
     *  hinq 2019 10 25
     *
     **/
    public function get_user_to_order_count(array $arr_where)
    {
        $raw = \DB::raw("count('*') as total , sum(pay_amount) as pay_amount ");
        return StoreOrder::select($raw)->where($arr_where)->get();
    }

    public function count_participant_activity_user(array $arr_where)
    {
        return StoreOrder::where($arr_where)->groupBy('user_id')->get()->count();
    }

    /**
     * 删除一条数据
     *
     * @param int $n_id
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function delete_one(int $n_id)
    {
        return StoreOrder::where('id', $n_id)->commondelete();
    }

    /**
     * 修改一条数据状态
     *
     * @param int $n_id
     * @param int $n_state
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function change_one_state(int $n_id, int $n_state)
    {
        return StoreOrder::where('id', $n_id)->update(['status' => $n_state]);
    }

    /**
     * 字段自增
     *
     * @param int $n_id
     * @param string $s_field
     * @param int $n_step
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function increase_num($n_id, $s_field = 'commend_num', $n_step = 1)
    {
        return StoreOrder::where('id', $n_id)->increment($s_field, $n_step);
    }

    /**
     * 字段自减
     *
     * @param int $n_id
     * @param string $s_field
     * @param int $n_step
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function decrease_num($n_id, $s_field = 'commend_num', $n_step = 1)
    {
        return StoreOrder::where('id', $n_id)->decrement($s_field, $n_step);
    }


    /**
     * 订单状态判断（商户端）
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function order_status($status, $pay_status)
    {
        $state = '';
        if ($status == 1 && $pay_status == 1) {
            $state = '待支付';
        } elseif ($status == 1 && $pay_status == 2) {
            $state = '待发货';
        } elseif ($status == 2) {
            $state = '已发货';
        } elseif ($status == 3) {
            $state = '待评价';
        } elseif ($status == 4) {
            $state = '已评价';
        } elseif ($status == 5) {
            $state = '已取消';
        } elseif ($status == 6) {
            $state = '申请退款';
        } elseif ($status == 7) {
            $state = '已退款';
        } elseif ($status == 8) {
            $state = '申请退货';
        } elseif ($status == 9) {
            $state = '已退货';
        } elseif ($status == 10) {
            $state = '异常单';
        } elseif ($status == 11) {
            $state = '拒绝退款';
        } elseif ($status == 12) {
            $state = '拒绝退货';
        } elseif ($status == 20) {
            $state = '已完成';
        }

        return $state;
    }

    /**
     * 定时任务获取三十分钟之内未支付的订单
     */
    public function all_auto_cancel_order($arr_select = ['*'], $n_minutes = 30)
    {
        $arr_where = ['status' => 1, 'pay_status' => 1];
        $s_time = time_to_ymdhis(time() - 60 * $n_minutes);

        return StoreOrder::where($arr_where)->where('created_at', '<', $s_time)->select($arr_select)->get();
    }

    /**
     * 取消订单回收库存
     */
    public function cancelOrderBackStock(int $order_id, $user_coupons_id = null)
    {
        if ($user_coupons_id) {
            //更新优惠券为未使用
            $up_coupon = ['id' => $user_coupons_id, 'status' => 1];
            CouponGrantDetailRepository::edit_one($up_coupon);
        }

        $arr_option['field'] = ['id', 'store_order_id', 'goods_product_id', 'goods_num'];
        $arr_option['where'] = ['store_order_id' => $order_id];
        $detail = StoreOrderGoodsRepository::get_all($arr_option)->toArray();

        foreach ($detail as $key => $value) {
            $id = $value['goods_product_id'];
            $num = $value['goods_num'];
            $result = GoodsProductRepository::increase_num($id, 'stock', $num);
        }
        if ($result) {
            return hello_success('库存回收成功');
        } else {
            return hello_error('库存回收失败');
        }
    }

    /**
     * 根据条件统计订单数量(公众号)
     */
    public function count_by_where(int $shop_id, int $time_cate, array $dayArray)
    {
        if ($time_cate == 2) {
            $raw = DB::raw("count(1) as total, DATE_FORMAT(created_at,'%Y-%m') as date ,sum(pay_amount) as amount");
            $between = [reset($dayArray), date('Y-m-d H:i:s', time())];
        } else {
            $raw = DB::raw("count(1) as total, DATE_FORMAT(created_at,'%Y-%m-%d') as date,sum(pay_amount) as amount");
            $between = [reset($dayArray), end($dayArray) . ' 23:59:59'];
        }

        //订单统计
        $days[1] = StoreOrder::select($raw)
            ->whereBetween('created_at', $between)
            ->where(['shop_id' => $shop_id])
            ->groupBy('date')
            ->get()->toArray();

        //总共的订单数
        $days[3] = StoreOrder::whereBetween('created_at', $between)
            ->where(['shop_id' => $shop_id])
            ->count();

        return $days;
    }

    /**
     * 发货十五天后确认收货
     * @return mixed
     */
    public function all_confirm_receipt()
    {
        $date = date('Y-m-d', strtotime("-15 day"));//15天前日期
        $receive_time = DB::raw("DATE_FORMAT(delivery_time,'%Y-%m-%d')");
        return StoreOrder::where($receive_time, $date)
            ->where(['status' => 2, 'is_finish' => 2])
            ->select(['id', 'is_finish', 'delivery_time'])
            ->get()
            ->toArray();
    }

    /**
     * 定时任务收货十五天后关闭订单
     */
    public function all_close_store_order()
    {
        $date = date('Y-m-d', strtotime("-15 day"));//15天前日期
        $receive_time = DB::raw("DATE_FORMAT(receive_time,'%Y-%m-%d')");
        return StoreOrder::where($receive_time, $date)
            ->where('is_finish', 2)
            ->select(['id', 'is_finish', 'receive_time'])
            ->get()
            ->toArray();
    }

    /**
     * 根据条件更新数据
     * @param array $orderIds
     * @param array $up_data
     * @return mixed
     */
    public function update_by_where_in($orderIds = [], $up_data = [])
    {
        return StoreOrder::whereIn('id', $orderIds)->update($up_data);
    }

    /**
     *  根据条件获取数量（开发票时检测当前订单是否可以开票）
     *  hinq 2020 6 15
     *
     **/
    public function get_count_whereIn( array $arr_whereIn = ['key'=>'id','value'=>[]]){
        return StoreOrder::whereIn($arr_whereIn['key'], $arr_whereIn['value'])->whereIn('is_invoice',[1,2])->count();
    }


}